package com.uenpay.im.ui.old.activity.remark;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qyx.android.database.DBFriendColumns;
import com.qyx.android.database.DBTopMsgColumns;
import com.qyx.android.database.FriendDB;
import com.qyx.android.database.TopListMsgManager;
import com.qyx.android.entity.FriendEntity;
import com.qyx.android.message.type.PacketType;
import com.uenpay.im.BroadcastAction;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.entities.QYXUserEntity;
import com.uenpay.util.app.base.BaseActivity;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * @author SL
 * @created 2016-3-22 下午4:48:25
 * @copyRight http://www.qiyunxin.com
 * @function 设置备注
 */
public class SetRemarkActivity extends BaseActivity {

    private TopListMsgManager topListMsgManager = new TopListMsgManager();
    private EditText remark_describe_edit, remark_name;
    private TextView remark_describe_count;
    private EditText phone_edit1, phone_edit2, phone_edit3, phone_edit4,
            phone_edit5;
    private String custid;
    private boolean is_update = false;
    private RemarkHandle mRemarkHandle = new RemarkHandle();
    private boolean is_friend = true;
    private View loading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isFullScreen = true;
        super.onCreate(savedInstanceState);
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_set_remark_layout;
    }

    @Override
    public void initView(View view) {
        if (getIntent() != null && getIntent().hasExtra("to_cust_id")) {
            custid = getIntent().getStringExtra("to_cust_id");
        }

        if (getIntent() != null && getIntent().hasExtra("is_update")) {
            is_update = getIntent().getBooleanExtra("is_update", true);
        }

        initView();
        initListener();
        if (is_update) {
            getRemark();
        }

        FriendEntity mFriendEntity = FriendDB.getFriend(custid);
        if (mFriendEntity == null || TextUtils.isEmpty(mFriendEntity.cust_id)) {
            is_friend = false;
        }
        getRemarkInfoByLoca();
    }

    protected void initView() {
        ((TextView) findViewById(R.id.title_textview))
                .setText(R.string.remark_info);
        loading = findViewById(R.id.loading);
        ((TextView) findViewById(R.id.title_right_tv)).setText(R.string.save);
        findViewById(R.id.title_right_layout).setVisibility(View.VISIBLE);
        remark_describe_edit = (EditText) findViewById(R.id.remark_describe_edit);
        remark_describe_count = (TextView) findViewById(R.id.remark_describe_count);
        remark_name = (EditText) findViewById(R.id.remark_name);

        phone_edit1 = (EditText) findViewById(R.id.phone_edit1);
        phone_edit2 = (EditText) findViewById(R.id.phone_edit2);
        phone_edit3 = (EditText) findViewById(R.id.phone_edit3);
        phone_edit4 = (EditText) findViewById(R.id.phone_edit4);
        phone_edit5 = (EditText) findViewById(R.id.phone_edit5);

        if (getIntent() != null && getIntent().hasExtra("userName")) {
            remark_name.setText(getIntent().getStringExtra("userName"));
        }
    }

    protected void initListener() {
        //返回键
        findViewById(R.id.back_layout).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                finish();
            }
        });
        findViewById(R.id.title_right_layout).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        String remarkName = remark_name.getText().toString();
                        String remarkDescribe = remark_describe_edit.getText()
                                .toString();
                        String phoneNum = "";
                        String phoneNum1 = phone_edit1.getText().toString();
                        String phoneNum2 = phone_edit2.getText().toString();
                        String phoneNum3 = phone_edit3.getText().toString();
                        String phoneNum4 = phone_edit4.getText().toString();
                        String phoneNum5 = phone_edit5.getText().toString();
                        if (!TextUtils.isEmpty(phoneNum1)) {
                            phoneNum = phoneNum1;
                        }
                        if (!TextUtils.isEmpty(phoneNum2)) {
                            if (TextUtils.isEmpty(phoneNum)) {
                                phoneNum = phoneNum2;
                            } else {
                                phoneNum = phoneNum + "," + phoneNum2;
                            }
                        }
                        if (!TextUtils.isEmpty(phoneNum3)) {
                            if (TextUtils.isEmpty(phoneNum)) {
                                phoneNum = phoneNum3;
                            } else {
                                phoneNum = phoneNum + "," + phoneNum3;
                            }
                        }
                        if (!TextUtils.isEmpty(phoneNum4)) {
                            if (TextUtils.isEmpty(phoneNum)) {
                                phoneNum = phoneNum4;
                            } else {
                                phoneNum = phoneNum + "," + phoneNum4;
                            }
                        }
                        if (!TextUtils.isEmpty(phoneNum5)) {
                            if (TextUtils.isEmpty(phoneNum)) {
                                phoneNum = phoneNum5;
                            } else {
                                phoneNum = phoneNum + "," + phoneNum5;
                            }
                        }
                        if (is_friend) {
                            setRemark(remarkName, phoneNum, remarkDescribe);
                        } else {
                            // 陌生人设置备注
                            setRemarkInfoToLoca(remarkName, phoneNum,
                                    remarkDescribe);
                        }
                    }
                });

        remark_describe_edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
                String remark_describe = remark_describe_edit.getText()
                        .toString();
                if (!TextUtils.isEmpty(remark_describe)
                        && remark_describe.length() > 200) {
                    remark_describe = remark_describe.substring(0, 200);
                    remark_describe_edit.setText(remark_describe);
                    remark_describe_edit.setSelection(remark_describe.length() - 1);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                int number = 200 - s.length();
                if (number >= 0) {
                    remark_describe_count.setText("" + number);
                }
            }
        });
    }

    private void setRemark(final String nickName, final String phoneNums, final String memo) {
        loading.setVisibility(View.VISIBLE);
        mRemarkHandle.setRemark(custid, nickName, phoneNums, memo,
                new RemarkHandle.ISetRemarkResultListener() {

                    @Override
                    public void setRemarkResult(int status, String msg) {
                        loading.setVisibility(View.GONE);
                        if (!TextUtils.isEmpty(msg)) {
                            IMApplication.showToast(msg);
                        }
                        if (status == HttpInvokeResultCode.RESULT_OK) {
                            udpateDBAndSendBroadCast(nickName);
                            setRemarkInfoToLoca(nickName, phoneNums, memo);
                        }
                    }
                });
    }

    private void getRemark() {
        loading.setVisibility(View.VISIBLE);
        mRemarkHandle.getRemark(custid, new RemarkHandle.IGetRemarkResultListener() {

            @Override
            public void onGetRemarkResult(int status, String msg,
                                          QYXUserEntity mQyxUserEntity) {
                loading.setVisibility(View.GONE);
                if (status != HttpInvokeResultCode.RESULT_OK) {
                    if (!TextUtils.isEmpty(msg)) {
                        IMApplication.showToast(msg);
                    }
                } else {
                    if (!TextUtils.isEmpty(mQyxUserEntity.remarkname)) {
                        remark_name.setText(mQyxUserEntity.remarkname);
                    }
                    if (!TextUtils.isEmpty(mQyxUserEntity.remarkMemo)) {
                        remark_describe_edit.setText(mQyxUserEntity.remarkMemo);
                    }

                    if (!TextUtils.isEmpty(mQyxUserEntity.remarkPhonenumber)) {
                        if (mQyxUserEntity.remarkPhonenumber.indexOf(",") > -1) {
                            String[] phoneNums = mQyxUserEntity.remarkPhonenumber
                                    .split(",");
                            phone_edit1.setText(phoneNums[0]);
                            phone_edit2.setText(phoneNums[1]);
                            if (phoneNums.length > 2) {
                                phone_edit3.setText(phoneNums[2]);
                            }
                            if (phoneNums.length > 3) {
                                phone_edit4.setText(phoneNums[3]);
                            }
                            if (phoneNums.length > 4) {
                                phone_edit5.setText(phoneNums[4]);
                            }
                        } else {
                            phone_edit1
                                    .setText(mQyxUserEntity.remarkPhonenumber);
                        }
                    }
                }
            }
        });
    }

    private void udpateDBAndSendBroadCast(String remark_name) {
        FriendEntity friendEntity = FriendDB.getFriend(custid);
        boolean is_success = FriendDB.updateFriend(custid,
                DBFriendColumns.REMARKS_NAME, remark_name);
        if (is_success) {
            sendBroadcast(new Intent(BroadcastAction.ACTION_REFRESH_FRIEND));
        }
        String chat_name = "";
        if (!TextUtils.isEmpty(remark_name)) {
            chat_name = remark_name;
        } else {
            if (friendEntity != null) {
                chat_name = friendEntity.nick_name;
            }
        }
        boolean is_send = false;
        if (topListMsgManager
                .updateTopMsgByField(Long.valueOf(custid), PacketType.PERSONAL,
                        DBTopMsgColumns.CHAT_NAME, chat_name) > 0) {
            is_send = true;
        }

        if (is_send) {
            Intent intent = new Intent(
                    BroadcastAction.ACTION_REFRESH_FRIEND_NAME);
            sendBroadcast(intent);
        }
    }

    private void setRemarkInfoToLoca(String remarkName, String phoneNum,
                                     String memo) {
        JSONObject json = new JSONObject();
        try {
            json.put("remark_name", remarkName);
            json.put("phone_num", phoneNum);
            json.put("memo", memo);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (json != null) {
            IMApplication.config.setStrangerFriendsJson(custid,
                    json.toString());
        }
        IMApplication.config.setFriendsRemarkName(custid, remarkName);
        setResult(RESULT_OK);
        finish();
    }

    /**
     * 获取陌生人备注
     */
    private void getRemarkInfoByLoca() {
        String content = IMApplication.config.getStrangerFriendsJson(custid);
        if (!TextUtils.isEmpty(content)) {
            try {
                JSONObject json = new JSONObject(content);
                if (json != null) {
                    if (json.has("remark_name")) {
                        String remarkName = json.optString("remark_name");
                        if (!TextUtils.isEmpty(remarkName)) {
                            remark_name.setText(remarkName);
                        }
                    }
                    if (json.has("memo")) {
                        String memo = json.optString("memo");
                        if (!TextUtils.isEmpty(memo)) {
                            remark_describe_edit.setText(memo);
                        }
                    }

                    if (json.has("phone_num")) {
                        String phone_num = json.optString("phone_num");
                        if (!TextUtils.isEmpty(phone_num)) {
                            if (phone_num.indexOf(",") > -1) {
                                String[] phoneNums = phone_num.split(",");
                                phone_edit1.setText(phoneNums[0]);
                                phone_edit2.setText(phoneNums[1]);
                                if (phoneNums.length > 2) {
                                    phone_edit3.setText(phoneNums[2]);
                                }
                                if (phoneNums.length > 3) {
                                    phone_edit4.setText(phoneNums[3]);
                                }
                                if (phoneNums.length > 4) {
                                    phone_edit5.setText(phoneNums[4]);
                                }
                            } else {
                                phone_edit1.setText(phone_num);
                            }
                        }
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onBackPressed() {
        finish();
        super.onBackPressed();
    }

}
